<?php

namespace app\store\controller;

use think\Db;
use think\Request;

/**
 * 日志管理
 * Class Log
 * @package app\store\controller
 */
class Log extends Controller
{
    public function index()
    {
        // 获取查询参数
        $request   = request();
        $search    = $request->get('search', '');
        $startTime = $request->get('start_time', '');
        $endTime   = $request->get('end_time', '');
        $adminUser = $request->get('admin_user', '');

        // **获取所有管理员**
        $adminUsers = Db::name('store_user')
            ->where('wxapp_id', $this->getWxappId())
            // ->where('is_delete', "0")
            ->field('store_user_id, user_name')
            ->select();

        // 构建查询
        $query = Db::name('admin_log')
            ->alias('log')
            ->join('yoshop_store_user user', 'log.admin_user_id = user.store_user_id', 'LEFT')
            ->field('log.*, user.user_name')
            ->where('log.wxapp_id', $this->getWxappId())
            ->order('log.create_time', 'desc');

        // **搜索操作描述**
        if (!empty($search)) {
            $query->where('log.operation_desc', 'like', "%$search%");
        }

        // **按时间范围筛选**
        if (!empty($startTime)) {
            $query->where('log.create_time', '>=', strtotime($startTime));
        }
        if (!empty($endTime)) {
            $query->where('log.create_time', '<=', strtotime($endTime) + 86400);
        }

        // **按管理员筛选**
        if (!empty($adminUser)) {
            $query->where('log.admin_user_id', $adminUser);
        }

        // **获取分页数据，并保留原有参数**
        $list = $query->paginate(15, false, [
            'query' => array_merge(request()->get(), ['s' => '/store/log/index']),
        ]);
        // dump($list);die();
        return $this->fetch('index', compact('list', 'search', 'startTime', 'endTime', 'adminUser', 'adminUsers'));
    }
    /**
     * 清空日志
     */
    public function clear()
    {
        Db::name('admin_log')->where('wxapp_id', $this->getWxappId())->delete();
        return $this->renderSuccess('日志已清空');
    }
}